﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using ZK.Common;

namespace ZK.Common
{
    public class TestConnect
    {
        /// <summary>
        /// test tcpip
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        public static bool TestConnectIp(string ip, int port)
        {
            bool res = false;
            int seconds = Convert.ToInt32(AppConfigHelper.GetAppSettings("WebSocketTime"));
            System.Diagnostics.Stopwatch swThd = System.Diagnostics.Stopwatch.StartNew();
            IPAddress iPAddress = IPAddress.Parse(ip);
            IPEndPoint point = new IPEndPoint(iPAddress, port);
            using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                Task.Factory.StartNew(() =>
                {
                    try
                    {
                        sock.Connect(point);
                        res = true;
                    }
                    catch (Exception e)
                    {
                        Common.Log4.LogManage.WriteErr("TestConnectIp " + ip + ":" + e.Message);
                    }
                }).Wait(seconds * 1000);
                sock.Close();
                if (!res) Common.Log4.LogManage.WriteErr(ip + ":连接超时、ip端口不正确");
                return res;
            }
        }

        /// <summary>
        /// Ping固定IP 如果不通，写数据异常
        /// </summary>
        /// <param name="str_ip">IP地址</param>
        /// <returns>成功返回1，失败返回0</returns>
        public static void CheckDeviceStatus(string str_ip, string name)
        {
            Ping pinSender = new Ping();
            PingOptions options = new PingOptions();
            string data = "";
            byte[] buffer = Encoding.ASCII.GetBytes(data);
            options.DontFragment = true;
            int timeout = Convert.ToInt32(AppConfigHelper.GetAppSettings("PingIpTime"));
            PingReply reply = pinSender.Send(str_ip, timeout, buffer, options);
            if (reply.Status != IPStatus.Success)
            {
                string msg = "ip:" + str_ip + " 名称：" + name + " 信息：网络异常，ping失败";
                WebApiService.AddHardWareLog(name, 1, msg);
                Common.Log4.LogManage.WriteErr(msg);
            }
        }
    }
}
